﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.IO;

namespace RazorTemplateEngine
{
    public class TemplateResult : ActionResult
    {
        public string OriginalTemplatePath { get; set; }

        public TemplateDataDictionary TemplateData { get; set; }

        public override object Execute(AssemblyContext assemblyContext)
        {
            if (string.IsNullOrEmpty(OriginalTemplatePath)) throw new ArgumentNullException("OriginalTemplatePath");

            ExecuteContext context = new ExecuteContext();
            context.tempData = TemplateData;
            context.ChildBody = null;
            context.srcTemplatePath = new FileInfo(OriginalTemplatePath).DirectoryName;
            context.assemblyContext = assemblyContext;

            //if not cache , build it!
            DynamicAssemblyCache asmCache = new DynamicAssemblyCache(OriginalTemplatePath, context);

            Assembly compiledAssembly = asmCache.GetAssemblyFromRazor();
            //execute
            TemplatePageExecutor executor = new TemplatePageExecutor(compiledAssembly);
            return executor.Execute(context);
        }
    }
}
